<template>
  <div v-loading="loading" class="game_banner">
    <div class="game_banner_bg">
      <img :src="getStaticFileUrl(gameInfo.backgroundImage)" alt="">
    </div>
    <div class="game_content">
      <div class="game_logo_name">
        <img class="game_logo" :src="getStaticFileUrl(gameInfo.logoImage)" alt="">
        <span class="game_name gl_db_ellipsis">{{ gameInfo.name }}</span>
      </div>
      <div class="game_detaile gl_clear">
        <div class="left_detaile_message">
          <div class="game_detaile_item gl_clear">
            <div style="width: 80px" class="gl_fl">
              主办单位：
            </div>
            <div style="width: 260px" class="gl_fl">
              <!-- 仅显示前两个主办单位 -->
              <div v-if="sponsorList[0]" class="gl_ellipsis" :title="sponsorList[0].organizationName"> {{ sponsorList[0].organizationName }} </div>
              <!-- 因空间布局调整，与产品商定后，仅显示第一个主办单位 2021年8月9日18:06:19 -->
              <!-- <div v-if="sponsorList[1]" class="gl_ellipsis" :title="sponsorList[1].organizationName"> {{ sponsorList[1].organizationName }} </div> -->
            </div>
          </div>
          <div class="game_detaile_item">
            <span>比赛时间：</span>
            <span>
              {{ gameInfo.startTime ? gameInfo.startTime.slice(0, 10) : '-' }}
              ~
              {{ gameInfo.endTime ? gameInfo.endTime.slice(0, 10) : '-' }}
            </span>
          </div>
          <div class="statistics_row">
            <img class="session_img" src="@/assets/images/league/gold_num.png" alt="">
            <span class="txt">共举办场次</span>
            <span class="txt_num">{{ statistics.isolateCompetitionCount }}</span>

            <img class="session_img" src="@/assets/images/league/org_num.png" alt="">
            <span class="txt">参赛单位</span>
            <span class="txt_num">{{ statistics.delegationCount }}</span>

            <img class="session_img" src="@/assets/images/league/person_num.png" alt="">
            <span class="txt">参赛人次</span>
            <span class="txt_num">{{ statistics.athleteCategoryCount }}</span>
          </div>
          <div class="game_entry_btn">
            <div v-if="gameInfo.statusCode !== 'Finished' && gameInfo.approveStatusCode === 'ApproveSuccess' && gameInfo.isPublished && isShowEntryBtn" class="entry_btn gl_mr_10" @click="clickJump('SubstationList')">
              申办比赛
            </div>
            <!-- <div
              v-if="gameInfoStatusCode === 'EntryStarted' && gameInfo.approveStatusCode === 'ApproveSuccess' && gameInfo.isPublished && isShowEntryBtn"
              class="entry_btn"
              @click="clickJump('Logistics')"
            >
              选择服务
            </div> -->
          </div>
          <div v-if="gameInfo.entryNotice || gameInfo.disclaimerNotice || gameInfo.regulation" class="game_rules">
            赛事相关条例：
            <a v-if="gameInfo.entryNotice" class="download_file" @click="downloadFile(gameInfo.entryNotice, '报名须知')">《报名须知》</a>
            <a v-if="gameInfo.disclaimerNotice" class="download_file" @click="downloadFile(gameInfo.disclaimerNotice, '免责声明')">《免责声明》</a>
            <a v-if="gameInfo.regulation" class="download_file" @click="downloadFile(gameInfo.regulation, '竞赛规程')">《竞赛规程》</a>
          </div>
        </div>
        <div class="right_qrcode">
          <div id="qrcode" class="qr_code" />
          <div class="qr_msg">微信扫码联赛小程序</div>
        </div>
      </div>
    </div>
    <div class="cust">
      <el-button type="success" icon="el-icon-phone-outline" round @click="()=>{visible='ture'}">联系客服</el-button>
    </div>
    <el-dialog title="联系客服" width="30%" :visible.sync="visible">
      <div class="customerImg">
        <img class="customer" src="@/assets/images/customer.png" alt="">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { getToken } from '@/lib/auth';
import QRCode from 'qrcodejs2';
import {
  api_GET_EventsManagementCompetitionWithRoute,
  api_GET_EventsManagementCompetitionOrganization,
  api_GET_EventsManagementCompetitionRequestCompetitionLeagueIndexDataLeagueCompetitionId // 联赛下数据管理-联赛数据统计(联赛首页)
} from '@/extend/api/gameswaggerApi/app';

export default {
  name: 'GameBanner',
  props: {
    isShowEntryBtn: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      visible: false,
      baseUrl: `${process.env.VUE_APP_API_SWAGGER_GAME}`,
      fileUrl: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}`,
      tokenInfo: getToken(),
      loading: false,
      gameInfo: {},
      statistics: {},
      committionList: [], // 各种单位列表，主办、协办……
      sponsorList: [], // 主办单位列表
      wxQrCodeBaseUrl: `${WEB_CONFIG.VUE_APP_API_WXQRCODE}`
    };
  },
  computed: {
    gameInfoStatusCode () {
      const _gameInfo = this.gameInfo.status || {};
      return _gameInfo.code;
    },
    isInGameCycle () { // 是否在比赛周期内
      if (this.gameInfo.startTime && this.gameInfo.endTime) {
        let _today = new Date();
        const _year = _today.getFullYear();
        const _month = _today.getMonth() >= 9 ? _today.getMonth() : '0' + _today.getMonth();
        const _date = _today.getDate();
        _today = _year + '-' + _month + '-' + _date;

        const _start = this.gameInfo.startTime.slice(0, 10);
        const _end = this.gameInfo.endTime.slice(0, 10);
        if (_today >= _start && _today <= _end) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    }
  },
  created() {
    const $route = this.$route;
    const _paramsId = $route.params.id;
    this.gameRoute = _paramsId.split('_')[0];
    // 因为短域名原因手动添加VUE_APP_Get_TenantId
    this.tenantId = process.env.VUE_APP_Get_TenantId;
    this.getGameInfoByGameRoute();
  },
  mounted() {
    this.createdQrCode();
  },
  methods: {
    // 生成二维码
    createdQrCode() {
      const _this = this;
      new QRCode('qrcode', {
        width: 155,
        height: 155,
        text: `${_this.wxQrCodeBaseUrl}?a=league_${_this.$route.params.id}`
        // text: `${location.origin}/mbleague.html#/home/${_this.$route.params.id}/info`
      });
      // https://manage-test.wtwuxicenter.com/wx_qrcode?a=league_mfss
    },
    // 根据赛事路由获取赛事信息
    getGameInfoByGameRoute() {
      const gameQO = {};
      gameQO.route = this.gameRoute;
      gameQO.IncludeStatus = true;
      gameQO.IncludeLevel = true;
      if (this.tenantId) {
        gameQO.__tenant = this.tenantId;
      }
      this.loading = true;
      api_GET_EventsManagementCompetitionWithRoute(gameQO).then(res => {
        this.loading = false;
        this.gameInfo = res || {};
        this.gameId = this.gameInfo.id;
        this.getPlayerStatistics(res.id);
        this.getCommittionList(res.id);
        this.$emit('getGameInfoSuccess', this.gameInfo);
      });
    },
    // 获取运动员统计
    getPlayerStatistics(id) {
      api_GET_EventsManagementCompetitionRequestCompetitionLeagueIndexDataLeagueCompetitionId(id)
        .then(
          res => {
            this.statistics = res;
            this.$emit('getStatistics', this.statistics);
            console.log(res);
          }
        );
    },
    // ===
    // 获取指定组委会单位列表
    getCommittionList(id) {
      this.committeeLoading = true;
      api_GET_EventsManagementCompetitionOrganization({ competitionId: id })
        .then(
          res => {
            this.committeeLoading = false;
            const committionList = res.items || [];
            this.committionList = this.handleShowCommittion(committionList);
          },
          error => {
            this.$message({ type: 'error', message: (error.error && error.error.message || '') });
            this.committeeLoading = false;
          }
        );
    },
    // 处理显示组委会
    handleShowCommittion(committionList) {
      const _committionList = {};
      const returnCommittionList = [];
      for (let i = 0; i < committionList.length; i++) {
        const item = committionList[i];
        _committionList[item.organizationKey] = _committionList[item.organizationKey] || [];
        _committionList[item.organizationKey].push(item);
      }
      // 主办单位
      if (_committionList.sponsor) {
        returnCommittionList.push({
          name: '主办单位',
          data: _committionList.sponsor
        });
        this.sponsorList = _committionList.sponsor;
      }
      // 承办单位
      if (_committionList.contractor) {
        returnCommittionList.push({
          name: '承办单位',
          data: _committionList.contractor
        });
      }
      // 支持单位
      if (_committionList.support) {
        returnCommittionList.push({
          name: '支持单位',
          data: _committionList.support
        });
      }
      // 协办单位
      if (_committionList.assistance) {
        returnCommittionList.push({
          name: '协办单位',
          data: _committionList.assistance
        });
      }
      // 联系电话
      if (_committionList.phone) {
        returnCommittionList.push({
          name: '联系电话',
          data: _committionList.phone
        });
      }
      return returnCommittionList;
    },
    // ===
    // 获取文件地址
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 处理背景图
    handleBackgroundImg(relatvieUrl) {
      return `url('${this.getStaticFileUrl(relatvieUrl)}');`;
    },
    // 点击跳转页面
    clickJump(name) {
      this.$router.push({
        name: name,
        query: { id: this.gameId }
      });
    },
    downloadFile(fileUrl, fileName) {
      axios({
        methods: 'get',
        url: `${this.fileUrl}${fileUrl}`,
        responseType: 'blob'
      }).then(res => {
        var blob = new Blob([res.data]);
        const suffix = fileUrl.split('.')[fileUrl.split('.').length - 1];
        if ('msSaveOrOpenBlob' in navigator) {
          window.navigator.msSaveOrOpenBlob(blob, fileName + '.' + suffix);
          return;
        }
        const downloadElement = document.createElement('a');
        const href = window.URL.createObjectURL(res.data);
        downloadElement.style.display = 'none';
        downloadElement.href = href;
        // downloadElement.download = fileName + '.' + suffix;
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
      }).catch(error => {
        errorText(error.response.data).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    }
  }
};
</script>

<style scoped>
.game_banner {
  position: relative;
  width: 1200px;
  height: 298px;
  border-radius: 8px;
  box-shadow: 0px 16px 70px 0px rgba(0,0,0,0.10);
  margin: 20px auto;
  overflow: hidden;
}
.game_banner_bg {
  float: left;
  width: 555px;
  height: 298px;
  border-radius: 10px;
  overflow: hidden;
}
.game_banner_bg img {
  width: 100%;
  height: 100%;
  vertical-align: middle;
  border-radius: 8px 0 0 8px;
}
.game_content {
  float: left;
  width: calc(100% - 555px);
  padding: 8px 20px 8px 20px;
  box-sizing: border-box;
}
.game_logo_name {
  display: flex;
  justify-content: center;
  align-items: center;
  align-content: center;
}
.game_logo_name .game_logo {
  width: 63px;
  height: 63px;
  margin-right: 16px;
  border-radius: 50%;
  vertical-align: middle;
}
.game_logo_name .game_name {
  width: calc(100% - 80px);
  font-size: 24px;
  line-height: 24px;
  vertical-align: middle;
}
.left_detaile_message {
  position: relative;
  float: left;
  margin-top: 21px;
  width: 360px;
}
.left_detaile_message::after {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  background: #31456C;
  width: 2px;
  height: 155px;
}
.left_detaile_message .game_detaile_item {
  padding-right: 10px;
  font-size: 16px;
  line-height: 24px;
  margin-bottom: 4px;
}
.game_entry_btn {
  width: 100%;
  height: 82px;
  padding: 19px 0 10px 0;
  box-sizing: border-box;
}
.game_entry_btn .entry_btn {
  width: 180px;
  height: 44px;
  background: #dc1d1d;
  border-radius: 8px;
  font-size: 16px;
  line-height: 47px;
  color: #fff;
  cursor: pointer;
  text-align: center;
  transition: all 0.3s ease;
  display: inline-block;
}
.game_entry_btn .entry_btn:hover {
  opacity: 0.8;
}
.game_rules {
  font-size: 14px;
  color: #353434;
}
.game_rules .download_file {
  color: #dc1d1d;
  font-weight: 700;
}
.game_rules .download_file:hover {
  text-decoration: underline;
}
.right_qrcode {
  width: 240px;
  padding-left: 20px;
  float: left;
  font-size: 16px;
  text-align: left;
  padding-top: 20px;
}
.statistics_row {
  width: 100%;
  padding-top: 16px;
  overflow: hidden;
  font-size: 12px;
  line-height: 14px;
  font-weight: 400;
  color: #828282;
}

.statistics_row .session_img {
  width: 14px;
  height: 14px;
  vertical-align: top;
  margin-right: 4px;
}
.statistics_row .txt {
  display: inline-block;
  vertical-align: top;
  margin-right: 6px;
}
.statistics_row .txt_num {
  display: inline-block;
  min-width: 35px;
  color: #DC1D1D;
  font-weight: 500;
  vertical-align: top;
}
.qr_code {
  width: 155px;
  height: 155px;
  margin-bottom: 9px;
}
.qr_msg {
  width: 155px;
  height: 24px;
  font-size: 16px;
  font-weight: 400;
  text-align: center;
  color: #000;
  line-height: 24px;
}
.customerImg {
    /* position: fixed;
    top: 80px;
    right: 10px;
    border-radius: 1px; */
    display: flex;
    justify-content: center;
    align-items: center;
}
.cust {
    position: fixed;
    bottom: 300px;
    margin-left: 1222px;
    border-radius: 1px;
    z-index: 999;
}
.customer {
  width: 440px;
  margin: 0 auto;
}
.el-button  ::v-deep  i {
  font-size: 20px;
}
.el-button  ::v-deep  span {
  font-size: 20px;
}
</style>
